package com.yunmang.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.yunmang.R;
import com.yunmang.entity.EndModel;

import java.util.List;

/**
 * Created by Administrator on 2017/5/4.
 */
public class SortListAdapter extends BaseAdapter implements SectionIndexer {
    private Context context;
    private List<EndModel> endModels;
    public SortListAdapter(Context context,List<EndModel> endModels){
        this.context=context;
        this.endModels=endModels;
    }

    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     * @param list
     */
    public void updateListView(List<EndModel> list){
        this.endModels = list;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return endModels.size();
    }

    @Override
    public Object getItem(int i) {
        return endModels.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        EndModel endModel = endModels.get(position);
        ViewHolder holder=null;
        if(convertView==null){
            holder=new ViewHolder();
            convertView=View.inflate(context, R.layout.item_end, null);
            holder.tv_category=(TextView) convertView.findViewById(R.id.catalog);
            holder.tv_Name=(TextView) convertView.findViewById(R.id.title);
            convertView.setTag(holder);
        }else{
            holder=(ViewHolder) convertView.getTag();
        }
        //获得首字母的ascii值
        int section = getSectionForPosition(position);
        if(position==getPositionForSection(section)){
            holder.tv_category.setVisibility(View.VISIBLE);
            holder.tv_category.setText(endModel.firstLetter);
        }else{
            holder.tv_category.setVisibility(View.GONE);
        }
        holder.tv_Name.setText(endModel.subModel.getName());
        return convertView;
    }

    @Override
    public Object[] getSections() {
        return new Object[0];
    }
    /**
     * 根据分组的首字母获取其第一次出现在列表中的位置
     * @param section
     * @return
     */
    @Override
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = endModels.get(i).firstLetter;
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 根据listview的当前位置获得获取分类首字母char的aciii值
     * @param position
     * @return
     */
    @Override
    public int getSectionForPosition(int position) {
        return endModels.get(position).firstLetter.charAt(0);
    }

    class ViewHolder{
        TextView tv_category;
        TextView tv_Name;
    }

}
